package com.origin.app.page.location_records

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Pair
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.databinding.ObservableLong
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.PolylineOptions
import com.amap.api.maps.utils.SpatialRelationUtil
import com.amap.api.maps.utils.overlay.SmoothMoveMarker
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.origin.app.MyApplication
import com.origin.app.R
import com.origin.app.bean.CompanyPointBean
import com.origin.app.databinding.ActivityLocationRecordsBinding
import com.origin.app.page.base.BaseActivity
import com.origin.app.page.map.AppMapActivity
import com.origin.app.utils.AppUtils
import com.origin.app.utils.MapUtils
import com.origin.utils.log.LogUtils
import kotlinx.coroutines.delay
import java.util.Timer
import java.util.TimerTask


class LocationRecordsActivity :
    BaseActivity<ActivityLocationRecordsBinding, ActivityLocationRecordsViewModel>(R.layout.activity_location_records),
    View.OnClickListener {
    companion object {
        fun launcher(companyPointBean: CompanyPointBean) {
            MyApplication.getInstance().getCurrentActivity()?.apply {
                val intent = Intent(this, LocationRecordsActivity::class.java)
                intent.putExtra("companyPointBean", companyPointBean)
                startActivity(intent)
            }
        }
    }

    var startTime = ObservableLong()
    var endTime = ObservableLong()
    lateinit var companyPointBean: CompanyPointBean
    override fun initContentView() {
        if (!intent.hasExtra("companyPointBean")) {
            throw RuntimeException("companyPointBean is null")
        }
        companyPointBean = intent.getSerializableExtra("companyPointBean") as CompanyPointBean
        contentViewBinding.selectCompanyPointBean = companyPointBean
        contentViewBinding.llStartTime.setOnClickListener(this)
        contentViewBinding.llEndTime.setOnClickListener(this)
        //
        contentViewBinding.tvResetRun.setOnClickListener(this)
        contentViewBinding.startTime = startTime
        contentViewBinding.endTime = endTime
        //mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        endTime.set(System.currentTimeMillis())
    }
   var smoothMoveMarker: SmoothMoveMarker?=null
    var markerLocation: Marker?=null
    override fun setMutableLiveDataListener() {

        viewModel.refreshCompanyPointBeanInfoMutableLiveData.observe(this){
            companyPointBean.refreshByLocation(it)
        }

        viewModel.refreshLocationRecordsMutableLiveData.observe(this) {
            var polyline = contentViewBinding.mapViewLocation.map.addPolyline(
                PolylineOptions().addAll
                    (viewModel.locationRecordsLatLng).width(20f).color(Color.BLUE)
            )
            LogUtils.__e("地图长度=====>  ${viewModel.locationRecordsLatLng.size}")
            MapUtils.fitMarkersToBoundsByLatLng(viewModel.locationRecordsLatLng, contentViewBinding.mapViewLocation.map)
            if(viewModel.locationRecordsLatLng.size==0){
                return@observe
            }

            if(true){

                viewModel.runLocationMarker(contentViewBinding.mapViewLocation.map)



                return@observe
            }

            smoothMoveMarker?.removeMarker()
            smoothMoveMarker = SmoothMoveMarker(contentViewBinding.mapViewLocation.map)
            smoothMoveMarker?.setDescriptor(BitmapDescriptorFactory.fromResource(R.mipmap.locate_arrow));

//            val drivePoint: LatLng = viewModel.locationRecordsLatLng[0]
//            val pair: Pair<Int, LatLng>? = SpatialRelationUtil.calShortestDistancePoint(viewModel.locationRecordsLatLng, drivePoint)
//            pair?.apply {
////                viewModel.locationRecordsLatLng[this.first] = drivePoint
//                val subList: List<LatLng> = viewModel.locationRecordsLatLng.subList(pair.first, viewModel.locationRecordsLatLng.size)
//                // 设置滑动的轨迹左边点
//
//
//            }

            smoothMoveMarker?.setPoints(viewModel.locationRecordsLatLng);
            // 设置滑动的总时间
            smoothMoveMarker?.setTotalDuration(40);
            // 开始滑动
            smoothMoveMarker?.startSmoothMove();

            smoothMoveMarker?.setMoveListener {
                LogUtils.__e("第几段 ${smoothMoveMarker?.index}  ， it : ${it}")
            }



        }
    }


    override fun initSavedInstanceState(savedInstanceState: Bundle?) {
        super.initSavedInstanceState(savedInstanceState)
        contentViewBinding.mapViewLocation.onCreate(savedInstanceState)
    }

    override fun onClick(view: View?) {
        if (view == null) {
            return;
        }
        if (view == contentViewBinding.llEndTime) {
            showDatePickerDialog("选择结束时间") {
                endTime.set(it)
                getLocationRecordsByTaskIdFun()
            }
            return;
        }
        if (view == contentViewBinding.llStartTime) {
            showDatePickerDialog("选择开始时间") {
                startTime.set(it)
                getLocationRecordsByTaskIdFun()
            }
            return;
        }
        if(view==contentViewBinding.tvResetRun){
            viewModel.runLocationMarker(contentViewBinding.mapViewLocation.map)
            return;
        }
    }

    private fun getLocationRecordsByTaskIdFun() {
        viewModel.getLocationRecordsByTaskId(companyPointBean, startTime.get(), endTime.get())
    }

    private fun showDatePickerDialog(title: String, callBack: (millisecond: Long) -> Unit) {
        CardDatePickerDialog.builder(this@LocationRecordsActivity)
            .setTitle(title)
            .showBackNow(false)
            .showDateLabel(true)
            .showFocusDateInfo(true)
            .setMaxTime(System.currentTimeMillis())
            .setDisplayType(
                DateTimeConfig.YEAR,
                DateTimeConfig.MONTH,
                DateTimeConfig.DAY,
                DateTimeConfig.HOUR,
                DateTimeConfig.MIN
            )
            .setOnChoose("选择", callBack)
            .setOnCancel("取消") {

            }.build().show()
    }


    override fun onDestroy() {
        super.onDestroy()
//        contentViewBinding.mapViewLocation.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        contentViewBinding.mapViewLocation.onResume()

    }

    override fun onPause() {
        super.onPause()
        contentViewBinding.mapViewLocation.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        contentViewBinding.mapViewLocation.onSaveInstanceState(outState)
    }

}